import re
from json import JSONDecodeError
import requests

# 获取user-agent,用于身份识别
header = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36'}



def downWritefile(aduio_url,title,index):
    path=index    #把这个路径改成你自己的
    with open(path+title+r'.mp3',"wb") as fd:
        response=Tools(aduio_url)   #请求并下载
        response.encoding = 'utf-8'
        fd.write(response.content)
        print('\n ：%s.mp3 下载成功!' %(title))



def getVedioURl(url,destDir):
    res = Tools(url)
    res.encoding = 'utf-8'
    text = res.text
    print(text)
    value = re.findall('{"id":(.*?),"title":"(.*?)"', text)
    #用正则表达式寻找符合条件的，找到不同资源的id和名字,输出列表套元组
    # 在上面的正则表达式中，只会返回trackid和title里的东西，其他只是筛选条件，不返回的
    #print(value)
    try:
        num= 1
        for x in value:     #抽取每个数据块的数据
            print(x[0],x[1],num)
            urlsub='https://webapi.qingting.fm/api/mobile/channels/101220/programs/'+str(x[0])
            resData = Tools(urlsub)
            resData.encoding = 'utf-8'
            vedioData =resData.json()
            #print(vedioData)
            if vedioData:
                itemURl=vedioData.get('programInfo')
                aduio_url=itemURl.get('audioUrl')
                downWritefile(aduio_url,str(num),destDir)

    except JSONDecodeError:
        pass



def Tools(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.70'
    }
    response = requests.get(url, headers=headers)
    return response



if __name__ == '__main__':
    #三国演义
    #url = "https://webapi.qingting.fm/api/mobile/channels/431209/programs?version=5eb6cedb740967693fe6fb3fd6955343&pageIndex=2&pageSize=30"
    destDir ='D:/var/qingan/'
    # https://webapi.qingting.fm/api/mobile/channels/431209/programs/20223928
    for i in range(1,14):
        #url = "https://www.qingting.fm/channels/431209/"+str(i)

        #情感双曲线
        url = "https://www.qingting.fm/channels/101220/"+str(i)

        getVedioURl(url,destDir)